package com.example.intelligentattendancesystem.service.impl;

import com.example.intelligentattendancesystem.mapping.UserMapping;
import com.example.intelligentattendancesystem.pojo.User;
import com.example.intelligentattendancesystem.service.FileUpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author
 * @version 1.0
 * @className FileUpServiceImpl
 * @since 1.0
 */
@Service
public class FileUpServiceImpl implements FileUpService {
    @Autowired
    UserMapping userMapping;
    @Override
    public String upFileService(MultipartFile img, int userId) {
        FileOutputStream fileOutputStream=null;
        String url="static/日程表.png";
        File file = new File("static/"+userId);
//        File file = new File(userId+"");
        if(!file.exists()){
//            创建目录
            file.mkdirs();
        }
        try {
            byte[] bytes = img.getBytes();
            fileOutputStream = new FileOutputStream("static/"+userId+"/"+img.getOriginalFilename());
//            fileOutputStream = new FileOutputStream(userId+"/"+img.getOriginalFilename());
            fileOutputStream.write(bytes);
            url= img.getOriginalFilename();

            fileOutputStream.flush();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        User user = userMapping.selectUserByUserId(userId);
        user.setIcon(url);
        int i = userMapping.updateUser(user);
        return url;
    }
}
